package com.hmdp.listener;

import com.hmdp.entity.VoucherOrder;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.service.impl.VoucherOrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.hmdp.service.impl.VoucherOrderServiceImpl.SECKILL_ORDER_TOPIC;

/**
 * RocketMQ消费者（监听秒杀订单主题，处理数据库逻辑）
 * 注：@RocketMQMessageListener注解会自动创建消费线程，无需手动创建线程池
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = SECKILL_ORDER_TOPIC, // 监听的主题
        consumerGroup = "seckill_order_topic", // 消费者组（读取配置）
        consumeMode = ConsumeMode.CONCURRENTLY,
        consumeThreadNumber = 40
)
public class SeckillListener implements RocketMQListener<VoucherOrder> {
    @Autowired
    private VoucherOrderServiceImpl voucherOrderService;


    @Override
    public void onMessage(VoucherOrder voucherOrder) {
        try {
            // 处理订单（复用原有handleVoucherOrder逻辑）
            voucherOrderService.handleVoucherOrder(voucherOrder);
            log.info("RocketMQ消费成功，订单id：{}", voucherOrder.getId());
        } catch (Exception e) {
            log.error("RocketMQ消费失败，订单id：{}", voucherOrder.getId(), e);
            // 抛出异常，RocketMQ会自动重试（默认重试16次，可配置）
            throw new RuntimeException("订单处理失败，触发RocketMQ重试", e);
        }

    }

}


    
